import pandas as pd
from contextlib import contextmanager
from sqlalchemy import create_engine
from comm_tools.config import Config
from comm_tools.logger import log_progress

@contextmanager
def open_mysql():
    c = Config()
    engine = None
    try:
        connection_string = (f"mysql+mysqlconnector://{c.user}:{c.password}"
                             f"@{c.host}:{c.port}/{c.database}")
        engine = create_engine(connection_string)
        yield engine
    finally:
        if engine is not None:
            engine.dispose()

def load_to_MySQL_on_Cloud(df, sql_connection, table_name):
    try:
        df.to_sql(name=table_name, con=sql_connection, index=False, if_exists='append')
        log_progress("Data loaded to Database as a table.")
    except Exception as e:
        if "Duplicate" in str(e):
            log_progress("Data not loaded due to duplicate entry.")
        else:
            log_progress(str(e))
